package com.sx.config;

import com.alibaba.fastjson.JSONObject;
import com.sx.pay.PayFactory;
import com.sx.pay.model.AlipayParams;
import com.sx.pay.model.WepayParams;
import com.sx.pay.service.alipay.AliPayService;
import com.sx.pay.service.wepay.WxPayService;
import com.sx.service.system.IConfigService;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @author AdinZ
 * @date 2020/11/13 11:41
 * 支付服务工厂
 */
//@Component
public class PayConfig {
  //  @Bean
    public PayFactory createPayFactory(IConfigService configService) {
        PayFactory factory = new PayFactory();
        //支付宝配置
        JSONObject alipayConfig=configService.findConfig("alipay");
        //微信支付配置
        JSONObject wxPay=configService.findConfig("wx_pay");
        //支付宝支付
        factory.registered(new AliPayService(createAlipayParams(alipayConfig)));
        //微信App支付
        factory.registered(new WxPayService(this.createWepayParams("wx_app",wxPay,configService)));
        //微信公众号支付
        factory.registered(new WxPayService(this.createWepayParams("wx_public",wxPay,configService)));
        //微信小程序支付
        factory.registered(new WxPayService(this.createWepayParams("wx_mini",wxPay,configService)));

        return factory;
    }

    private AlipayParams createAlipayParams(JSONObject config){
        AlipayParams params=new AlipayParams();
        params.setAlipayPublicKey(config.getString("alipayPublicKey"));
        params.setAppId(config.getString("appId"));
        params.setPrivateKey(config.getString("privateKey"));
        params.setServerUrl(config.getString("serverUrl"));
        params.setNotifyUrl(config.getString("notifyUrl"));
        params.setReturnUrl(config.getString("returnUrl"));
        return params;
    }

    private WepayParams createWepayParams(String key,JSONObject config,IConfigService configService){
        WepayParams params=new WepayParams();
        JSONObject jsonObject = configService.findConfig(key);
        config.putAll(jsonObject);
        params.setAppId(config.getString("appId"));
        params.setApiKey(config.getString("apiKey"));
        params.setAppSecret(config.getString("appSecret"));
        params.setCertUrl(config.getString("certUrl"));
        params.setMchId(config.getString("mchId"));
        params.setNotifyUrl(config.getString("notifyUrl"));
        params.setReturnUrl(config.getString("returnUrl"));
        return params;
    }


}
